// pages/personal/diary/diary.js
const db = wx.cloud.database()
const _ = db.command
const col = "diary"
const sql = {
  _id: _.neq(1)
} //获取所有记录


Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    isEndOfList: false,
    listlength: 0,
    limit: 5 //每次拉取数量
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const openid = wx.getStorageSync('openid')
    if (!openid) {
      wx.reLaunch({
        url: '/pages/personal/personal',
      })
    }
  },
  deleteDiary(e) {

    const id = e.currentTarget.dataset.id
    wx.showModal({
      title: '是否确认删除',
      content: '该操作将删除该条日记',
      success(res) {
        if (res.confirm) {
          wx.cloud.callFunction({
            name: "deletediary",
            data: {
              _id: id
            },
            success(res) {
              if (res.result.errMsg == 'collection.remove:ok') {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success',
                  duration: 2000
                })
                const pages = getCurrentPages()
                const perpage = pages[pages.length - 1]
                perpage.onShow()

              }
            },
            fail(err) {
              console.log(err, 'errs');
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // wx.hideLoading()
  },
  getDiaryList(openid) {
    wx.showLoading({
      title: '加载中',
    })
    db.collection(col)
      .where(sql)
      .skip(this.data.list.length)
      .limit(this.data.limit)
      .get()
      .then(res => {
        console.log(res);
        if (res.errMsg == "collection.get:ok") {
          wx.hideLoading()
        }
        this.setData({
          listlength: [...this.data.list, ...res.data].length,
          list: [...this.data.list, ...res.data], //合并数据
          isEndOfList: res.data.length < this.data.limit ? true : false //判断是否结束
        })
      })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const openid = wx.getStorageSync('openid')
    this.getDiaryList(openid)
  },
  toTop() {
    wx.pageScrollTo({
      scrollTop: 0
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('触底加载');
    const openid = wx.getStorageSync('openid')
    this.data.isEndOfList || this.getDiaryList(openid)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})